// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package adwords.axis.v201109.misc;

import com.google.api.ads.adwords.axis.v201109.cm.Campaign;
import com.google.api.ads.adwords.axis.v201109.cm.CampaignPage;
import com.google.api.ads.adwords.axis.v201109.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201109.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.client.AdWordsSession.Environment;
import com.google.api.ads.adwords.lib.factory.AdWordsServices;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.http.javanet.NetHttpTransport;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * This example demonstrates how to authenticate using OAuth.  This example
 * is meant to be run from the command line and requires user input.
 *
 * @author Adam Rogal
 */
public class OAuthExample {

  @SuppressWarnings("unused")
  private static final String PRODUCTION_SCOPE = "https://adwords.google.com/api/adwords";
  private static final String SANDBOX_SCOPE = "https://adwords-sandbox.google.com/api/adwords";

  public static void main(String[] args) throws Exception {
    // Set the OAuth consumer key and secret. Anonymous values can be used for
    // testing, and real values can be obtained by registering your application:
    // http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html
    String consumerKey = "anonymous";
    String consumerSecret = "anonymous";

    // Create the HMAC signer.
    OAuthHmacSigner signer = new OAuthHmacSigner();
    signer.clientSharedSecret = consumerSecret;

    // Construct the client to get the temporary token.
    GoogleOAuthGetTemporaryToken oAuthGetTemporaryToken =
        new GoogleOAuthGetTemporaryToken();

    oAuthGetTemporaryToken.consumerKey = consumerKey;
    // Set this to PRODUCTION_SCOPE if production is used instead of sandbox.
    oAuthGetTemporaryToken.scope = SANDBOX_SCOPE;
    oAuthGetTemporaryToken.signer = signer;
    oAuthGetTemporaryToken.displayName = "INSERT_DISPLAY_NAME_HERE";
    oAuthGetTemporaryToken.transport = new NetHttpTransport();

    // Request a new OAuth token. Web applications should pass in a callback
    // URL to redirect the user to after authorizing the token using
    // oAuthGetTemporaryToken.build(). "oob" is used in this case to display
    // the verification code on the screen.
    oAuthGetTemporaryToken.callback = "oob";
    OAuthCredentialsResponse oAuthCredentialResponse = oAuthGetTemporaryToken.execute();

    // Construct the URL to authorize a temporary token.
    GoogleOAuthAuthorizeTemporaryTokenUrl oAuthAuthorizeTemporaryTokenUrl =
        new GoogleOAuthAuthorizeTemporaryTokenUrl();
    String temporaryToken = oAuthCredentialResponse.token;
    oAuthAuthorizeTemporaryTokenUrl.temporaryToken = temporaryToken;

    // Set the token shared secret on the signer.
    signer.tokenSharedSecret = oAuthCredentialResponse.tokenSecret;

    // In a web application, you would redirect the user to the authorization
    // URL and after approving the token they would be redirected back to the
    // callback URL, with the URL parameter "oauth_verifier" added. For
    // desktop or server applications, spawn a browser to the URL and then
    // have the user enter the verification code that is displayed.
    System.out.printf("Log into your account with the following URL:\n%s\n",
        oAuthAuthorizeTemporaryTokenUrl.build());
    System.out
        .println("After approving the token, enter the verification code (oauth_verifier):");
    String verifier = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();

    // Construct the upgrade the authorized token.
    GoogleOAuthGetAccessToken oAuthGetAccessToken = new GoogleOAuthGetAccessToken();
    oAuthGetAccessToken.consumerKey = consumerKey;
    oAuthGetAccessToken.temporaryToken = temporaryToken;
    oAuthGetAccessToken.verifier = verifier;
    oAuthGetAccessToken.signer = oAuthGetTemporaryToken.signer;
    oAuthGetAccessToken.transport = new NetHttpTransport();

    // Upgrade the authorized token.
    oAuthCredentialResponse = oAuthGetAccessToken.execute();

    // Set the token secret.
    signer.tokenSharedSecret = oAuthCredentialResponse.tokenSecret;

    // Build OAuthParameters.
    OAuthParameters oAuthParameters = new OAuthParameters();
    oAuthParameters.version = "1.0a";
    oAuthParameters.token = oAuthCredentialResponse.token;
    oAuthParameters.consumerKey = consumerKey;
    oAuthParameters.signer = signer;

    AdWordsSession session = new AdWordsSession.Builder()
        .withOAuthParameters(oAuthParameters)
        .withDeveloperToken("INSERT_DEVELOPER_TOKEN_HERE")
        .withEnvironment(Environment.SANDBOX).build();

    session.setClientCustomerId("INSERT_CLIENT_CUSTOMER_ID_HERE");

    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        new AdWordsServices().get(session, CampaignServiceInterface.class);

    // Create selector.
    Selector selector = new Selector();
    selector.setFields(new String[] {"Id", "Name"});

    // Get all campaigns.
    CampaignPage page = campaignService.get(selector);

    // Display campaigns.
    if (page.getEntries() != null) {
      for (Campaign campaign : page.getEntries()) {
        System.out.println("Campaign with name \"" + campaign.getName() + "\" and id \""
            + campaign.getId() + "\" was found.");
      }
    } else {
      System.out.println("No campaigns were found.");
    }
  }
}
